package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @ClassName ApUserRealnameServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/12 17:55
 * @Version 1.0
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * @param dto 用户审核类对象
     * @return 用户认证表查询结果对象
     * @Description 按照状态查询用户认证列表
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1. 校验参数：分页数据不能为空，若为空设为默认值
        dto.checkParam();
        //2. 封装根据状态查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> page = page(new Page<>(dto.getPage(), dto.getSize()), queryWrapper);
        return PageResponseResult.page(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Resource
    private ApUserMapper apUserMapper;

    /**
     * @Description 实名认证审核
     * 2 审核失败   9 审核成功
     */
    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        // 1. 校验参数
        if (ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(dto.getId())) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 根据ID查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        if (ObjectUtils.isEmpty(userRealname)) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID, "该用户信息不存在");
        }
        // 3. 判断实名认证状态是否为待审核
        if (userRealname.getStatus().intValue() != 1) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID, "该用户状态有误");
        }
        // 4. 查询实名认证用户关联的ap_user信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (ObjectUtils.isEmpty(apUser)) {
            CustomException.custom(AppHttpCodeEnum.DATA_NOT_EXIST, "关联用户信息不存在");
        }
        // 5. 更新实名认证信息
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);
        // 6. 如果 审核结果为 通过(9) 生成自媒体账号，生成作者信息
        if (status.intValue() == AdminConstants.AD_USER_ISSTATUS) {
            WmUser wmUser = createWmUser(apUser);
            if (ObjectUtils.isEmpty(wmUser)) {
                CustomException.custom(AppHttpCodeEnum.SERVER_ERROR, "创建自媒体用户失败");
            }
            createAuthor(wmUser);
            apUser.setFlag((short) 1);
        }
        // 7. 设置当前用户为自媒体人
//        if (!IdCardUtils.checkIdCardInfo(userRealname.getName(), userRealname.getIdno())) {
//            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "姓名和身份证号认证不通过");
//        }
        apUser.setIdentityAuthentication(true);
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult();
    }

    @Resource
    private ArticleFeign articleFeign;

    /**
     * @Description 创建作者信息
     *
     * @param wmUser  自媒体用户对象
     */
    private void createAuthor(WmUser wmUser) {
        ApAuthor author = articleFeign.findByUserId(wmUser.getApUserId());
        if (author != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(wmUser.getName());
        author.setType(2);
        author.setUserId(wmUser.getApUserId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        articleFeign.save(author);
    }

    @Resource
    private WemediaFeign wemediaFeign;

    /**
     * @Description 创建自媒体用户
     * @param apUser 用户对象
     * @return 自媒体用户对象
     */
    private WmUser createWmUser(ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "自媒体用户已经存在");
        }
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(AdminConstants.AD_USER_ISSTATUS);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        return wemediaFeign.save(wmUser);
    }
}
